$(document).ready(function() {
	var columnCounter = 0;
	var columns = [];
	var numColumns = $('.commentContainer h1').length;
	var hiddenBooks;
	var hiddenVideos;
	var hiddenNotes;
	var hiddenOther;
	
	$('.WikispacesStream').hide();
	
	//defining our big string for the toc
	bigLongString = '';


	var stringForStyles = '<link rel="stylesheet" href="http://vanderbiltent.wikispaces.com/file/view/cjstylesheet16.css/512334444/cjstylesheet16.css" type="text/css" />';

	$('head').append(stringForStyles);
		
		$('.filterButton, #search-text').hover(
			function(){
				$(this).next().animate({opacity:'show', top: '-80'}, 'slow');
			},

			function(){
				$(this).next().animate({opacity:'hide', top: '-100'}, 'fast');
			}
		);


	// create and format the columns for the TOC
	for (var i = 1; i <= numColumns; i++){
		if ( i === 1 ){
			$("#toc_container").append("<div class='columnContainer' id='firstCol'><div class='tocColumn" + i + "'></div></div>");
		} else if (i != 1 && i != numColumns){
			$("#toc_container").append("<div class='columnContainer'><div class='tocColumn" + i + "'></div></div>");
		} else if (i = numColumns){
			$("#toc_container").append("<div class='columnContainer' id='lastCol'><div class='tocColumn" + i + "'></div></div>");
		} else {
			alert("col not found");
		}
	}
	
	// sets column widths of the TOC based on number of columns
	var colWidth = (100-2) / numColumns;
	$(".columnContainer").css( "width", colWidth + "%" );  
	
	// clearFloat needed to ensure everything below TOC is on a new line
	$("#toc_container").after("<div class='clearFloat'></div>");
	
	// populates TOC based on the headers in the HTML and gives them links to anchors
	var headerCounter = 0;
	$('.commentContainer h1, h2, h3, h4, h5, h6').each(function(){		
		var headerType = $(this).prop("nodeName");
		switch(headerType){
			case 'H1':
				headerCounter++; 
				var urlToEncode = $(this).text();
				var urlEncoded = (encodeURIComponent(urlToEncode));
				$(".tocColumn" + headerCounter + "").
				append("<p class='tocHeader'><a href='#" + urlEncoded + "'>" + $(this).text() + "</a></p>");
				break;
			case 'H2':
			case 'H3':
			case 'H4':
				var urlToEncode = $(".tocColumn" + headerCounter + " .tocHeader").text() + "--" + $(this).prop("nodeName") + " -- " + $(this).text();
				var urlEncoded = (encodeURIComponent(urlToEncode));
				$(".tocColumn" + headerCounter + "").
				append("<p class='tocLevel1'><a href=#" + urlEncoded + ">" + $(this).text() + "</a></p>");
				break;
			case 'H5':
				var urlToEncode = $(".tocColumn" + headerCounter + " .tocHeader").text() + "--" + $(this).prop("nodeName") + " -- " + $(this).text();
				var urlEncoded = (encodeURIComponent(urlToEncode));
				$(".tocColumn" + headerCounter + "").
				append("<p class='tocLevel2'><a href=#" + urlEncoded + ">" + $(this).text() + "</a></p>");
				break;
			case 'H6':
				var urlToEncode = $(".tocColumn" + headerCounter + " .tocHeader").text() + "--" + $(this).prop("nodeName") + " -- " + $(this).text();
				var urlEncoded = (encodeURIComponent(urlToEncode));
				$(".tocColumn" + headerCounter + "").
				append("<p class='tocLevel3'><a href=#" + urlEncoded + ">" + $(this).text() + "</a></p>");
				break;
		}
	});
	
	// makes the TOC columns the same height
	var maxHeight;
	function makeColsSameHeight() {
		maxHeight = Math.max.apply(null, $('div[class*="tocColumn"]').map(function(){
			return $(this).height();
			alert($(this).height());
		}).get())+20+'px';
		$('div[class*="tocColumn"]').each(function() {
			$(this).css({'height':maxHeight});
		});
	}
	makeColsSameHeight();
	function makeTOCHeadersSameHeight() {
		maxHeight = Math.max.apply(null, $('p[class*="tocHeader"]').map(function(){
			return $(this).height();
			alert($(this).height());
		}).get())+5 +'px';
		$('p[class*="tocHeader"]').each(function() {
			$(this).css({'height':maxHeight});
		});

	}
	makeTOCHeadersSameHeight();

	//adds links to the table of contents based upon the header contents
	var li_counter = 0;
	var currentSection;  
	$('.commentContainer h1, h2, h3, h4, h5, h6').each(function(){
		var element_text = $(this).text();
		if ($(this).prop("nodeName") === "H1"){
			currentSection = $(this).text();
			var urlEncoded = (encodeURIComponent(currentSection));
			$(this).prepend('<a name="' + urlEncoded + '" /></a.');  
		};
		if ($(this).prop("nodeName") === "H2" || 
			$(this).prop("nodeName") === "H3" ||
			$(this).prop("nodeName") === "H4" ||
			$(this).prop("nodeName") === "H5" ||
			$(this).prop("nodeName") === "H6" 
			)
				{
				var link_text = currentSection + "--" + $(this).prop("nodeName") + " -- " + $(this).text();
				var urlEncoded = (encodeURIComponent(link_text));
				$(this).prepend('<a name="' + urlEncoded + '" /></a.');  
			};
	});
	
	
	// changes background color slightly when section is moused over
	$('.box_background').mouseenter(function(){	
		$(this).css('background-color', '#F2F2F2');	
		$(this).find('p').css('color', '#6E6E6E');
	});
	$('.box_background').mouseleave(function(){
	    $(this).css('background-color', '#FAFAFA');
	    $(this).find('p').css('color', '#A4A4A4');
	});

	
	
	
	
function checkToSeeIfAllHidden(){
	// books
			var bookLIs = $('.wikiPage > div .books').find('li');
			var hiddenBookLIs = $('.wikiPage > div .books').find('.hidden');
			if ($(bookLIs).length !== $(hiddenBookLIs).length ){
				hiddenBooks = false;
			} else {
				hiddenBooks = true;
			};
	// other
			var otherLIs = $('.wikiPage > div .other').find('li');
			var hiddenOtherLIs = $('.wikiPage > div .other').find('.hidden');
			if ($(otherLIs).length !== $(hiddenOtherLIs).length ){
				hiddenOther = false;
			} else {
				hiddenOther = true;
			};
	// notes
			var notesLIs = $('.wikiPage > div .notes').find('li');
			var hiddenNotesLIs = $('.wikiPage > div .notes').find('.hidden');
			if ($(notesLIs).length !== $(hiddenNotesLIs).length  ){
				hiddenNotes = false;
			} else {
				hiddenNotes = true;
			};	
	// video
			var videoLIs = $('.wikiPage > div .videos').find('li');
			var hiddenVideoLIs = $('.wikiPage > div .videos').find('.hidden');
			if ($(videoLIs).length !== $(hiddenVideoLIs).length){
				hiddenVideos = false;
			} else {
				hiddenVideos = true;
			};
};


	function checkButtonColors(){
		if (hiddenBooks === true){
			$('#filterBooks').css('background-color', '#8A0808');  //red color
		} else {
			$('#filterBooks').css('background-color', '#088A29'); //green color			
		}
		
		if (hiddenOther === true){
			$('#filterOther').css('background-color', '#8A0808');  //red color
		} else {
			$('#filterOther').css('background-color', '#088A29'); //green color			
		}

		if (hiddenNotes === true){
			$('#filterNotes').css('background-color', '#8A0808');  //red color
		} else {
			$('#filterNotes').css('background-color', '#088A29'); //green color			
		}
		
		if (hiddenVideos === true){
			$('#filterVideos').css('background-color', '#8A0808');  //red color
		} else {
			$('#filterVideos').css('background-color', '#088A29'); //green color			
		}
	};
	
	// changes color of bottom right buttons slightly when  moused over

		$('#filterBooks').hover(
			function(){
				if (hiddenBooks === true){
					$('#filterBooks').css('background-color', '#B40404');  //red color
				} else {
					$('#filterBooks').css('background-color', '#04B431'); //green color
				};
			},
			function(){
				if (hiddenBooks === true){
					$('#filterBooks').css('background-color', '#8A0808');  //red color
				} else {
					$('#filterBooks').css('background-color', '#088A29'); //green color			
				}
			}
		);
		
		$('#filterOther').hover(
			function(){
				if (hiddenOther === true){
					$('#filterOther').css('background-color', '#B40404');  //red color
				} else {
					$('#filterOther').css('background-color', '#04B431'); //green color
				};
			},
			function(){
				if (hiddenOther === true){
					$('#filterOther').css('background-color', '#8A0808');  //red color
				} else {
					$('#filterOther').css('background-color', '#088A29'); //green color			
				}
			}
		);
	
		$('#filterNotes').hover(
			function(){
				if (hiddenNotes === true){
					$('#filterNotes').css('background-color', '#B40404');  //red color
				} else {
					$('#filterNotes').css('background-color', '#04B431'); //green color
				};
			},
			function(){
				if (hiddenNotes === true){
					$('#filterNotes').css('background-color', '#8A0808');  //red color
				} else {
					$('#filterNotes').css('background-color', '#088A29'); //green color			
				}
			}
		);		

		$('#filterVideos').hover(
			function(){
				if (hiddenVideos === true){
					$('#filterVideos').css('background-color', '#B40404');  //red color
				} else {
					$('#filterVideos').css('background-color', '#04B431'); //green color
				};
			},
			function(){
				if (hiddenVideos === true){
					$('#filterVideos').css('background-color', '#8A0808');  //red color
				} else {
					$('#filterVideos').css('background-color', '#088A29'); //green color			
				}
			}
		);
	

	
	
	//quick filters provided by the buttons on the lower right of the screen
	$('#filterBooks').click(function(){	
		if (!$('.books').hasClass('hidden')){
			$('.books li').addClass('hidden');	
			$('.books')	
			$(this).css('background-color', '#8A0808');
		} else {
			$('.books li').removeClass('hidden');
			$('.books').removeClass('hidden');
			$(this).css('background-color', '#088A29');
		}
		hideHeadersAndBoxes();
		checkToSeeIfAllHidden();
		checkButtonColors();
		document.getElementById("search-text").value = "";
	});

	$('#filterNotes').click(function(){	
		if (!$('.notes').hasClass('hidden')){
			$('.notes').addClass('hidden');	
			$('.notes li').addClass('hidden');	
			$(this).css('background-color', '#8A0808');
		} else {
			$('.notes').removeClass('hidden');
			$('.notes li').removeClass('hidden');
			$(this).css('background-color', '#088A29');
		}
		hideHeadersAndBoxes();
		checkToSeeIfAllHidden();
		checkButtonColors();
		document.getElementById("search-text").value = "";
	});	
	
	$('#filterOther').click(function(){	
		if (!$('.other').hasClass('hidden')){
			$('.other').addClass('hidden');
			$('.other li').addClass('hidden');
			$(this).css('background-color', '#8A0808');
		} else {
			$('.other').removeClass('hidden');
			$('.other li').removeClass('hidden');
			$(this).css('background-color', '#088A29');
		}
		hideHeadersAndBoxes();
		checkToSeeIfAllHidden();
		checkButtonColors();
		document.getElementById("search-text").value = "";
	});	
	
	$('#filterVideos').click(function(){	
		if (!$('.videos').hasClass('hidden')){
			$('.videos').addClass('hidden');	
			$('.videos li').addClass('hidden');	
			$(this).css('background-color', '#8A0808');
		} else {
			$('.videos').removeClass('hidden');
			$('.videos li').removeClass('hidden');
			$(this).css('background-color', '#088A29');
		}
		hideHeadersAndBoxes();
		checkToSeeIfAllHidden();
		checkButtonColors();
		document.getElementById("search-text").value = "";
	});

	
/*	SEARCH BOX CODE */
  //we want this function to fire whenever the user types in the search-box
  $("#search-text").keyup(function () {
    //first we create a variable for the value from the search-box
    var searchTerm = $("#search-text").val();
    //then a variable for the list-items (to keep things clean)
 //  var listItem = $('#list').children('li');
    var listItem = $('.commentContainer div ul').find('li');
    
    //extends the default :contains functionality to be case insensitive
    //if you want case sensitive search, just remove this next chunk
    $.extend($.expr[':'], {
      'containsi': function(elem, i, match, array)
      {
        return (elem.textContent || elem.innerText || '').toLowerCase()
        .indexOf((match[3] || "").toLowerCase()) >= 0;
      }
    });//end of case insensitive chunk

    //this part is optional
    //here we are replacing the spaces with another :contains
    //what this does is to make the search less exact by searching all words and not full strings
    var searchSplit = searchTerm.replace(/ /g, "'):containsi('")
    
    
    //here is the meat. We are searching the list based on the search terms
    $(".commentContainer div ul li").not(":containsi('" + searchSplit + "')").each(function(e)   {

          //add a "hidden" class that will remove the item from the list
          $(this).addClass('hidden');
    });
    
    //this does the opposite -- brings items back into view
    $(".commentContainer div ul li:containsi('" + searchSplit + "')").each(function(e) {

          //remove the hidden class (reintroduce the item to the list)
          $(this).removeClass('hidden');
    });

	// hides all the headers and boxes associated with list items that have already been hidden by the search box.
	hideHeadersAndBoxes();
	checkToSeeIfAllHidden();
	checkButtonColors();
	});
	
	// hides all the headers and boxes associated with list items that have already been hidden by the search box.
	function hideHeadersAndBoxes(){
		var allLiElementsForThisDiv;
		var numOfLiInDiv;
		var hiddenInDiv;
		var numOfHiddenInDiv;
		var hiddenCount = 0;
	
		$('.wikiPage > div').find('ul').each(function(){
			numListItems = $(this).find('li').length;
			numListItemsHidden = $(this).find('.hidden').length;
			if (numListItems === numListItemsHidden){
				//$(this).parent().hide();
				$(this).parent().addClass('hidden');	
			} else {
				$(this).parent().removeClass('hidden');
				//$(this).parent().show();
			};
		
		});

		$('#my_link_content > div').each(function(){
//			console.log("****************FUNCTION START**********************");
			
			hiddenCount = 0;
//			console.log(" list of li in each wikiPage > div = " + $(this).prop("nodeName") + " -- " + $(this).text());
			allLiElementsForThisDiv = $(this).find('li');
			numOfLiInDiv = $(allLiElementsForThisDiv).length;

			$(allLiElementsForThisDiv).each(function(){
//				console.log(" li and text: = " + $(this).prop("nodeName") + " -- " + $(this).text());
//				console.log(" li ?hidden: = " + $(this).hasClass('hidden'));

				if ($(this).hasClass('hidden')) {
					hiddenCount++;
				};
			});
			
			if (!$(this).hasClass('divider') && numOfLiInDiv === hiddenCount){
				$(this).addClass('hidden');
			} else {
				$(this).removeClass('hidden');
			};
//				console.log("numOfLiInDiv = " + numOfLiInDiv);
//				console.log("hiddenCount = " + hiddenCount);
		});	

		
	}
	
	
	// clears the search box when the x-button is pressed
	$('.clearSearch').click(function(){	
		document.getElementById("search-text").value = "";
		$("#search-text").keyup();
	});
	// clears the search box when the esc key is pressed
	$('input[type="text"]').keyup(function(e){
        if(e.keyCode == 27) {
            $(this).val('');
       		$("#search-text").keyup();
        }
    });

	function convertNaNToNumber(val){
		if (isNaN(val)){
			return 999;
		} else {
			return val;x
		};
	};


		
	checkToSeeIfAllHidden();
	checkButtonColors();

	
	
	
});	

